import requests
import json

singer = input("请输入你要下载的歌手名字:")
pages = int(input(f'请输入需要下载{singer}歌曲的页数:'))

for page in range(1, pages+1):
    url = f'http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={singer}&pn={page}&rn=30&httpsStatus=1&reqId=7b7b91a0-1ad7-11ed-b9a8-198e9cc3d87a'
    # 设置反爬
    headers = {
        'Cookie': '_ga=GA1.2.1814122629.1651482273; _gid=GA1.2.205632186.1660292719; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1660292719,1660351648; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1660374742; kw_token=2CX2HIT8EYG',
        'csrf': '2CX2HIT8EYG',
        'Referer': f'http://www.kuwo.cn/search/list?key=%E5%91%A8%E6%9D%B0%E4%BC%A6',  # 必须设置防盗链
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    # 解析数据 找到音乐的下载地址
    json_data = json.loads(response.text)  # 解析后的数据 为字典类型
    lists = json_data['data']['list']
    # 建立一个rid列表存储
    rids = []
    names = []  # 存储下载音乐的名称
    for lis in lists:
        rids.append(lis['rid'])
        names.append(lis['name'])
    # 定义一个下载列表 存储音乐下载地址
    load_list = []
    index = 0  # 用于定位名称
    print(f'正在下载音乐第{page}页')
    for rid in rids:
        name = names[index]
        index = index + 1
        music_url = f'http://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=mp3&httpsStatus=1&reqId=00a692f1-1adb-11ed-83a9-e917414cf877'
        music_response = requests.get(music_url)
        load_dic = json.loads(music_response.text)
        load_address = load_dic['data']['url']
        load_list.append(load_address)
        # 下载音乐
        f = open(f'音乐/{name}.mp3', 'wb')
        load_music = requests.get(load_address)
        f.write(load_music.content)  # 下载音乐
        print(f'第{page}页下载完成')
print('全部下载完成')
